package com.tianya.dream.system.controller;

import com.google.code.kaptcha.Producer;
import com.tianya.common.utils.uuid.IdUtils;
import com.tianya.common.web.constant.Constants;
import com.tianya.common.web.core.domain.AjaxResult;
import com.tianya.common.web.utils.VerifyImageUtil;
import com.tianya.common.web.utils.sign.Base64;
import com.tianya.dream.common.constants.UserConstants;
import com.tianya.dream.framework.web.service.VerifyCodeService;
import com.tianya.plugtool.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private VerifyCodeService verifyCodeService;

    /**
     * 验证码类型
     */
    @Value("${tianya.captchaType}")
    private String captchaType;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if (UserConstants.CAPTCHA_TYPE_MATH.equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if (UserConstants.CAPTCHA_TYPE_CHAR.equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    /**
     * 图片滑动验证码
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/getImageVerify")
    public AjaxResult getImageVerifyCode() {
        String IMG_PATH = "/image/login/*.*";
        //模板图
        String TEMP_IMG_PATH = "/image/module/*.*";
        // 随机读取一个背景图
        BufferedImage imageTemplate = getRandomImg(IMG_PATH);
        // 随机读取一个模板
        BufferedImage oriImage = getRandomImg(TEMP_IMG_PATH);
        // 根据模板裁剪图片
        Map<String, Object> resultMap = null;
        try {
            resultMap = VerifyImageUtil.pictureTemplatesCut(imageTemplate, oriImage);
            Double xWidth = Double.parseDouble(resultMap.get("xWidth").toString());
            //缓存记录key，项目实现 redis 或者 requset seesion
            // Cached.set(key, xWidth);
            String uuid = IdUtils.simpleUUID();
            String verifyKey = Constants.IMAGE_CODE_KEY + uuid;
            redisCache.setCacheObject(verifyKey, xWidth, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            //request.setAttribute("xWidth",xWidth);
            // 移除map的滑动距离，不返回给前端
            resultMap.remove("xWidth");
            resultMap.remove("widthRandom");
            resultMap.put("uuid", uuid);
            //resultMap 包含 背景图片和浮动图片
            return AjaxResult.success(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取验证码失败");
        }
    }

    /**
     * 校验滑块拼图验证码
     *
     * @param moveLength 移动距离
     * @return BaseRestResult 返回类型
     * @Description: 生成图形验证码
     * app办公端共用,修改后需通知手机开发人员
     */
    @GetMapping(value = "/verifyImageCode")
    public AjaxResult verifyImageCode(@RequestParam("moveLength") String moveLength, @RequestParam("uuid") String uuid) {
        Boolean bl = verifyCodeService.verifyImageCode(moveLength, uuid);
        if (bl) {
            return AjaxResult.success("验证通过", bl);
        }
        return AjaxResult.error("验证不通过", bl);
    }

    private BufferedImage getRandomImg(String path) {
        //获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 获取远程服务器IP和端口
        try {
            //获取所有匹配的文件
            org.springframework.core.io.Resource[] resources = resolver.getResources(path);
            //随机数
            int randNum = new Random().nextInt(resources.length);
            BufferedImage image = ImageIO.read(resources[randNum].getInputStream());
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
